package com.dr.controller.index;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dr.entity.Shopcart;
import com.dr.entity.User;
import com.dr.service.ShopcartService;
import com.dr.util.LayUiResult;
@Controller
@RequestMapping("/index/")
public class ShopcartController {
	@Autowired
	private ShopcartService shopcartService;
	/**
	 * 我的购物车跳转
	 */
		@RequestMapping("/findShopcarts.do")
		public String findShopcarts(HttpSession session,Model model) {
			User user = (User) session.getAttribute("loginUser");
			List<Shopcart> list=shopcartService.findShopcarts(user.getId());
			model.addAttribute("list",list);
			return "cart.jsp";
			
		}
		/**
		 * 删除购物车商品
		 */
		@RequestMapping("/deleteShopcart.do")
		@ResponseBody
		public Map<String, Object> deleteShopcart(String ids) {
			int num=shopcartService.deleteShopcart(ids);
			return num >0 ?LayUiResult.toClient("0", "成功") :LayUiResult.toClient("1", "失败");
		}
		
		/**
		 * 数量的加和减
		 */
		@RequestMapping(value = "/updateCount.do",method = RequestMethod.POST)
		@ResponseBody
		public Map<String, Object> updateCount(Integer id,String option) {
			int num=shopcartService.updateCount(id, option);
			return num >0 ?LayUiResult.toClient("0", "成功") :LayUiResult.toClient("1", "失败");
		}
		
		/**
		 * 添加购物车
		 */
		@RequestMapping("/addShopcart.do")
		@ResponseBody
		public Map<String, Object> addShopcart(HttpSession session, Shopcart shopcart) {
			User user=(User) session.getAttribute("loginUser");
			Shopcart isCart=shopcartService.findISSamePro(shopcart.getPro_id(), user.getId(), shopcart.getSize());
			int rel=0;
			if(isCart!=null) {
				rel=shopcartService.addShopcartByUpdateCount(isCart.getId(), shopcart.getCount());
			}else {
				shopcart.setUser_id(user.getId());
				shopcart.setTotalSum(shopcart.getPrice()*shopcart.getCount());
				rel=shopcartService.addShopcart(shopcart);
			}
			return rel >0 ?LayUiResult.toClient("0", "成功") :LayUiResult.toClient("1", "失败");
		}
}
